<?php

namespace app\admin\controller\dealer;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Config;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Support;
use GuzzleHttp\Client;
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column;

/**
 * @ControllerAnnotation(title="mall_order")
 */
class Order extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\mall\Order();
        
    }
    /**
     * @NodeAnotation(title="退款")
     */
    public function refund($id){
        // print_r($id); exit;
        // 获取请求参数  
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        $orderData = $this->model->find($id);
        if ($orderData->refund_status == 1) {
            $this->error('订单已退款,请勿重复退款');
        }
        // $transactionId = '4200002360202411029636777833'; // 微信订单号  
        // $outRefundNo = '1730540911122745';    // 商户退款单号  
        // $totalFee = 100;           // 原订单金额  
        // $refundFee = 100;         // 退款金额  
        $transactionId = $orderData->transaction_id; // 微信订单号  
        $outRefundNo = $orderData->order_sn;    // 商户退款单号  
        $totalFee = $orderData->ok_amount *100;           // 原订单金额  
        $refundFee = $orderData->ok_amount *100;         // 退款金额  

        // 配置微信支付  
        // $config = Config::get('easywechat.payment');  
        $config = [
            'app_id'        => Config::get('app')['const_data']['appid'],         // 必填，公众号的唯一标识  
            'mch_id'        => Config::get('app')['const_data']['mch_id'],         // 必填，商户号  
            'key'           => Config::get('app')['const_data']['secret_key'],        // 必填，API密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            // 'cert_path'   => '/www/wwwroot/hosj4bb2pabe-5768.beijing-02.dayunet.com/public/pays/apiclient_cert.pem', // 可选，商户证书路径  
            // 'key_path'      => '/www/wwwroot/hosj4bb2pabe-5768.beijing-02.dayunet.com/public/pays/apiclient_key.pem',  // 可选，商户证书密钥路径  
            'cert_path'   => 'D:/phpstudy_pro/WWW/jingxiaoshang/prod_jingxiaoshang/distributor/public/pays_dev/apiclient_cert.pem', // 可选，商户证书路径  
            'key_path'      => 'D:/phpstudy_pro/WWW/jingxiaoshang/prod_jingxiaoshang/distributor/public/pays_dev/apiclient_key.pem',  // 可选，商户证书密钥路径  
            'notify_url'    => Config::get('app')['const_data']['refund_notify_url'], // 可选，异步通知地址  
            // 其他配置项...  
        ];
        // print_r($config); exit;

        $orderData = $this->model->find($id);
        if ($orderData->refund_status == 1) {
            $this->error('订单已退款,请勿重复退款');
        }
        $app = Factory::payment($config);
        $update_time = time();
        // 日志
        $refundModel = new \app\admin\model\mall\Refund;  
        $refundData = [
            'transaction_id' => $orderData->transaction_id,
            'order_sn' => $orderData->order_sn,
            'total_fee' => $orderData->ok_amount,
            'order_id' => $orderData->id,
            'user_id' => $orderData->user_id,
            'status' => 1,
        ];
        //事务
        $this->model->startTrans();
        try {
            // 发起退款请求  参数分别为：微信订单号、商户退款单号、订单金额、退款金额、其他参数
            $result = $app->refund->byTransactionId($transactionId, $outRefundNo, $totalFee, $refundFee, [  
                // 'refund_desc'   => 'Refund description', // 退款原因  
                'notify_url'    => Config::get('app')['const_data']['refund_notify_url'], // 可选，退款结果通知网址  
            ]);
            // print_r($result); exit;
            // 返回结果  
            if ($result['return_code'] === 'SUCCESS' || $result['result_code'] === 'SUCCESS') {  
                // 订单
                $orderData->order_status = 9;
                $orderData->logistics_status = 9;
                $orderData->refund_status = 1;
                $orderData->update_time = $update_time;
                // 日志
                $refundData['content'] = $result['err_code_des']??'';
                $refundData['create_time'] = $update_time;
                if (!$refundModel->insert($refundData) || !$orderData->save()) {
                    $this->model->rollback();
                    throw new \Exception('订单退款失败');
                }
            } else {  
                // 日志
                $refundData['content'] = '退款失败';
                $refundData['create_time'] = $update_time;
                $refundModel->insert($refundData);
            }
            
        } catch (\Exception $e) {
            $this->model->rollback();
            $this->error('退款失败:'.$e->getMessage());
        }
        $this->model->commit();
        $this->success('退款成功');
    }
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->where('indent_status',0)
                ->where('pay_status',1)
                ->count();
            $list = $this->model
                ->field('ea_mall_order.* 
                    ,(SELECT name FROM ea_company_identity WHERE id = ea_mall_order.salesman_id AND ea_mall_order.pay_status=1) AS identity_supplier
                    ,(SELECT phone FROM ea_company_identity WHERE id = ea_mall_order.salesman_id AND ea_mall_order.pay_status=1) AS supplier_phone
                    ,(SELECT CONCAT(shop_name," ",name) FROM ea_company_identity WHERE id = ea_mall_order.shop_id AND ea_mall_order.pay_status=1) AS identity_shop
                    ,(SELECT phone FROM ea_company_identity WHERE id = ea_mall_order.shop_id AND ea_mall_order.pay_status=1) AS shop_phone
                ')
                // ,(SELECT name FROM ea_company_identity WHERE id = ea_mall_order.shop_id) AS identity_shop 
                ->where($where)
                ->where('pay_status',1)
                ->where('indent_status',0)
                ->page($page, $limit)
                ->order($this->sort)
                // ->fetchsql(true)
                ->select();
            $goodsModel = new \app\admin\model\mall\Goods;
            $goodsData = $goodsModel->where('is_default',1)->find();
            foreach ($list as $key => &$value) {
                // $value['salesman_remind'] = ($value['salesman_remind']==0) ?$goodsData['goods_remind']:$value['salesman_remind'];
                // $value['shop_remind'] = ($value['shop_remind']==0) ?$goodsData['goods_remind']:$value['shop_remind'];
                $value['goods_name'] = $goodsData->name;
                $value['goods_images'] = $goodsData->images;
            }
            // 修改订单提点佣金
            // print_r($list); exit;
            $remindOrder = $this->model
                ->where('pay_status',1)
                ->where('indent_status',0)
                ->where('remind_status',0)
                ->select()->toArray();
                // print_r($remindOrder); exit;
            if (!empty($remindOrder)) {
                $remindData = [];
                // 业务员提点
                $goods_remind_json = unserialize($goodsData->goods_remind_json);
                // 获取店铺佣金
                $identity_shop = array_filter(array_column($remindOrder,'shop_id','shop_id'));
                $identity_shop_id = implode(',',$identity_shop);
                $identityModel = new \app\admin\model\company\Identity();
                $identityData = $identityModel->where([['id','in',$identity_shop_id]])->column('shop_remind_price','id');
                // 利润
                $profit = number_format(($goodsData->price - $goodsData->purchase_price - $goodsData->shipping_cost),2,".","") ??0.00;
                // print_r($profit); exit;
                foreach ($remindOrder as $k => $v) {
                    if ($v['remind_status'] == 0) {
                        if ($v['shop_id'] > 0) {
                            // 计算店铺佣金
                            $remindData[$k]['id'] = $v['id'];
                            $remindData[$k]['remind_status'] = 1;
                            $remindData[$k]['shop_remind'] = ($identityData[$v['shop_id']]) ?number_format(($identityData[$v['shop_id']]*$v['goods_num']),2,".",""):0.00;
                            // 经销商 利润=售价-供货价(原进价)-运营物流费-(业务员提点|门店提点)
                            $remindData[$k]['dealer_profit'] = number_format((($profit*$v['goods_num']) - $remindData[$k]['shop_remind']),2,".",""); //经销商
                        } else if($v['salesman_id'] > 0) {
                            // 计算业务员提点 
                            $salesman_remind = 0;
                            foreach ($goods_remind_json as $vv) {
                                if ($v['goods_num']>=$vv[1] && $v['goods_num']<=$vv[2]) {
                                    $salesman_remind = $vv[0];
                                }
                            }
                            $remindData[$k]['id'] = $v['id'];
                            $remindData[$k]['remind_status'] = 1;
                            $remindData[$k]['salesman_remind'] = $this->truncate_to_two_decimals($salesman_remind*$v['ok_amount']/100); //业务员提点
                            // 经销商 利润=售价-供货价(原进价)-运营物流费-(业务员提点|门店提点)
                            $remindData[$k]['dealer_profit'] = number_format((($profit*$v['goods_num']) - $remindData[$k]['salesman_remind']),2,".",""); //经销商
                        }
                    }
                }
                // print_r($remindData); exit;
                if (!empty($remindData)) {
                    //事务 修改订单提点佣金
                    $this->model->startTrans();
                    try {

                        if (!$this->model->saveAll($remindData)) {
                            $this->model->rollback();
                            throw new \Exception('修改订单提点佣金失败');
                        }
                    } catch (\Exception $e) {
                        $this->model->rollback();
                        $this->error('保存失败:'.$e->getMessage());
                    }
                    $this->model->commit();
                }
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->layoutBgColor();
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }
}